<?php
include_once 'application/controllers/AbstractController.php';
require_once 'application/models/Batterie.php';
require_once 'application/models/Exercice.php';

class BatterieController extends AbstractController 
{

	private static $_TYPE_MACHINE = 1;
	
	function indexAction()
    {
		parent::indexAction();
    	HttpUtil::do405();
    }
    
    
    function getAction()
    {
		parent::getAction();
    	
		// get params
		$id = $this->getRequest()->getParam('id');
		$readMode = $this->getRequest()->getParam('r');
		// get Batterie from id
	    $batterie = new Batterie();
		
		$wherePublicReading = $batterie->getAdapter()->quoteInto('(visibility_id < ?)',Batterie::$_VISIBILITY_PRIVATE);
		$whereOwner = $batterie->getAdapter()->quoteInto('(owner_id = ?)', $this->user->id);
	    $where = $batterie->getAdapter()->quoteInto('id = ?', $id);
	    $batterieRows = $batterie->fetchAll(array($where, $wherePublicReading.' OR '.$whereOwner));
	    
    	//check asnwer : 404 if not found
	    if (isset($batterieRows[0])) {
	    	if (isset($readMode) && $readMode != "") {
			    $result = $batterie->getObjectFromRow($batterieRows[0], true);
	    	}else{
			    $result = $batterie->getObjectFromRow($batterieRows[0], false);
	    	}

		    // render
			$this->view->data = json_encode($result, JSON_FORCE_OBJECT);
	    }else{
			HttpUtil::do404();
	    }
    }
    
    /**
     * 
     * Return a list of batteries. 
     * - If "tid" param is set, all batteries with this type id 
     *   are returned, with their exezrcices
     * - Else, all batteries are returned, without thier exercices
     */
    function listAction()
    {
		// get params
		$tid = $this->getRequest()->getParam('tid');
		$ids = $this->getRequest()->getParam('ids');
		$writable = ($this->getRequest()->getParam('w') == '1');
		
		$list = Batterie::listBatteries($tid, $ids, $writable, $this->user);
		if ($list === false ){
			HttpUtil::do404();
		}else{
			$this->view->data = json_encode($list, JSON_FORCE_OBJECT);
		}
    }    
    
    function postAction()
    {
		parent::postAction();
		
		// get params
		$nom = $this->getRequest()->getParam('nom');
		$description = $this->getRequest()->getParam('description');
		$numero_enabled = $this->getRequest()->getParam('numero_enabled');
		$dictee_enabled = $this->getRequest()->getParam('dictee_enabled');
		$default_tempo = $this->getRequest()->getParam('default_tempo');
		$pagePerSerie = $this->getRequest()->getParam('pagePerSerie');
		$questionPerPage = $this->getRequest()->getParam('questionPerPage');		
		$visibilityId = $this->getRequest()->getParam('visibilityId');		

		$batterie_type_id = self::$_TYPE_MACHINE;
		
		$ownerId = $this->user->id;
		
		$table = new Batterie();
		
		// check params type
		$isValid = TypeChecker::validate(array(
			array('data' => $nom, 'type' => TypeChecker::$_TEXT_TYPE, 'name' => 'nom'),
			array('data' => $description, 'type' => TypeChecker::$_TEXT_UNLIMITED_TYPE, 'name' => 'description'),
			array('data' => $batterie_type_id, 'type' => TypeChecker::$_NUM_TYPE, 'name' => 'batterie_type_id'),
			array('data' => $numero_enabled, 'type' => TypeChecker::$_BOOL_TYPE, 'name' => 'numero_enabled'),
			array('data' => $dictee_enabled, 'type' => TypeChecker::$_BOOL_TYPE, 'name' => 'dictee_enabled'),
			array('data' => $default_tempo, 'type' => TypeChecker::$_BOOL_TYPE, 'name' => 'default_tempo'),
			array('data' => $pagePerSerie, 'type' => TypeChecker::$_NUM_TYPE, 'name' => 'pagePerSerie'),
			array('data' => $visibilityId, 'type' => TypeChecker::$_NUM_TYPE, 'name' => '$visibility_id'),
			array('data' => $questionPerPage, 'type' => TypeChecker::$_NUM_TYPE, 'name' => 'questionPerPage')
		));
		if ($isValid !== true) {
			HttpUtil::do400('validation', $isValid);
		}
		
	    // insert the new batterie
		try {
			$data = array(
				'nom' => $nom,
				'description' => $description,
				'batterie_type_id' => $batterie_type_id,
				'numero_enabled' => $numero_enabled,
				'dictee_enabled' => $dictee_enabled,
				'default_tempo' => $default_tempo,
				'page_per_serie' => $pagePerSerie,
				'question_per_page' => $questionPerPage,
				'visibility_id' => $visibilityId,
				'owner_id' => $ownerId
			);
			
			$lastInsertId = $table->insert($data);	    
		}catch(Exception $exception) {
			print_r($exception);exit;
			HttpUtil::do400('creation_failed');
		}
	    
		HttpUtil::set201();

		// get created batterie
		$table = new Batterie();
		$where = $table->getAdapter()->quoteInto('id = ?', $lastInsertId);
	    $batRows = $table->fetchAll($where);
	    
	    // return the created coloc
	    if (isset($batRows[0])) {
			$this->view->data = json_encode($table->getArrayFromRow($batRows[0]));
	    }else{
			HttpUtil::do400('getting_failed');
	    }
    }

    
    
    
    function putAction()
    {
		parent::putAction();
		
		// get params
		$id = $this->getRequest()->getParam('batterie_id');
		$nom = $this->getRequest()->getParam('nom');
		$description = $this->getRequest()->getParam('description');
		$visibilityId = $this->getRequest()->getParam('visibilityId');
		$pagePerSerie = $this->getRequest()->getParam('pagePerSerie');
		$questionPerPage = $this->getRequest()->getParam('questionPerPage');
		$numero_enabled = $this->getRequest()->getParam('numero_enabled');
		$dictee_enabled = $this->getRequest()->getParam('dictee_enabled');
		$default_tempo = $this->getRequest()->getParam('default_tempo');
				
		// check params type
		$isValid = TypeChecker::validate(array(
			array('data' => $id, 'type' => TypeChecker::$_NUM_TYPE, 'name' => 'id'),
			array('data' => $nom, 'type' => TypeChecker::$_TEXT_TYPE, 'name' => 'nom'),
			array('data' => $description, 'type' => TypeChecker::$_TEXT_UNLIMITED_TYPE, 'name' => 'description'),
			array('data' => $visibilityId, 'type' => TypeChecker::$_NUM_TYPE, 'name' => 'visibilityId'),
			array('data' => $pagePerSerie, 'type' => TypeChecker::$_NUM_TYPE, 'name' => 'pagePerSerie'),
			array('data' => $questionPerPage, 'type' => TypeChecker::$_NUM_TYPE, 'name' => 'questionPerPage'),
			array('data' => $numero_enabled, 'type' => TypeChecker::$_BOOL_TYPE, 'name' => 'numero_enabled'),
			array('data' => $dictee_enabled, 'type' => TypeChecker::$_BOOL_TYPE, 'name' => 'dictee_enabled'),
			array('data' => $default_tempo, 'type' => TypeChecker::$_BOOL_TYPE, 'name' => 'default_tempo')
		));
		if ($isValid !== true) {
			HttpUtil::do400('validation', $isValid);
		}
    	
		// get Batterie and check owner
		$table = new Batterie();
		$where = array();
		$where[] = $table->getAdapter()->quoteInto('(id = ?)', $id);
		$where[] = $table->getAdapter()->quoteInto('(owner_id = ?)', $this->user->id);
	    $batterieRows = $table->fetchAll($where);
	    
	    if (!isset($batterieRows[0])) {
	    	HttpUtil::do401();
	    }
		
		// update table
		try {
			$data = array(
				'nom' => $nom,
				'description' => $description,
				'visibility_id' => $visibilityId,
				'page_per_serie' => $pagePerSerie,
				'question_per_page' => $questionPerPage,
				'numero_enabled' => $numero_enabled,
				'dictee_enabled' => $dictee_enabled,
				'default_tempo' => $default_tempo
			);
			
			$where = $table->getAdapter()->quoteInto('id = ?', $id);

			$numberOfRows = $table->update($data, $where);

		}catch(Exception $exception) {
			HttpUtil::do400('update_failed');
		}
		// we do not check the number of rows, 'cause in the case of putting the same
		// data that the existing one : then, numberofrows = 0 (although it's a success)
		
	    //return 200
    }
    
    
    
    function deleteAction()
    {
		parent::deleteAction();

		// get params
		$id = $this->getRequest()->getParam('id');
		
		try {
			// check rights
			$tableB = new Batterie();
			$where = array();
		    $where[] = $tableB->getAdapter()->quoteInto('id = ?', $id);
		    $where[] = $tableB->getAdapter()->quoteInto('owner_id = ?', $this->user->id);
		    $batterieRows = $tableB->fetchAll($where);
		    if (!isset($batterieRows[0])) {
		    	HttpUtil::do400('not_owner');
		    }
			
			// delete
			$tableS = new Serie();
			$where = $tableS->getAdapter()->quoteInto('batterie_id = ?', $id);
			$numberOfRows = $tableS->delete($where);
			
			$tableE = new Exercice();
			$where = $tableE->getAdapter()->quoteInto('batterie_id = ?', $id);
			$numberOfRows = $tableE->delete($where);
			
			$tableB = new Batterie();
			$where = $tableB->getAdapter()->quoteInto('id = ?', $id);
			$numberOfRows = $tableB->delete($where);
			
		}catch(Exception $exception) {
			HttpUtil::do400('delete_failed');
		}
	    
	    // check the number of rows deleted
	    if ($numberOfRows < 1) {
			HttpUtil::do404();
	    }
    }
}
